package com.aierkeji.b2c.service;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.aierkeji.b2c.constants.Contants;
import com.aierkeji.b2c.dao.jpa.AkjAlipayLifeSnapDao;
import com.aierkeji.b2c.entity.snapshot.AkjAlipayLifeSnap;
import com.aierkeji.b2c.utils.StringUtils;

@Service
public class AkjAlipayLifeService {
	@Value("${server.servlet.context-path}")
	private String path;
	
	@Autowired
	private AkjAlipayLifeSnapDao akjAlipayLifeSnapDao;

	private final Logger log = LogManager.getLogger(getClass());


	public AkjAlipayLifeSnap findById(String id) {
		Optional<AkjAlipayLifeSnap> option = akjAlipayLifeSnapDao.findById(id);
		if(option.isPresent()) {
			return option.get();
		}
		return null;
	}
	public AkjAlipayLifeSnap findByLifeId(String lifeId) {
		Optional<AkjAlipayLifeSnap> option = akjAlipayLifeSnapDao.findFirstByLifeIdAndDeleteOrderByIdDesc(lifeId,false);
		if(option.isPresent()) {
			return option.get();
		}
		return null;
	}


	public String login(String lifeId) throws Exception {
		// TODO Auto-generated method stub
		AkjAlipayLifeSnap akjAlipayLifeSnap = this.findById(lifeId);
		if(akjAlipayLifeSnap!=null) {
			Map<String, Object>map = new HashMap<>();
			map.put("appId", akjAlipayLifeSnap.getLifeId());
			map.put("redirect_uri",URLEncoder.encode(Contants.BASE_URL+path.substring(1,path.length())+"/gateway/login_back/"+lifeId,"UTF-8"));
			String url = StringUtils.processTemplate(Contants.LOGIN_URL, map);
			log.info("重定向url:{}", url);
			return url;
		}else {
			log.info("error lifeId:{}", lifeId);
		}
		return null;
	}
	


}
